import subprocess
import time

import pandas as pd
import os
import threading
import hashlib
from common.initpath import oldtxtsave, newtxtsave, init_txt_dir, oldexcelsave, newexcelsave


def xls_to_txt(excel_dir_path: str, target: str):
    init_txt_dir(target)
    files = os.listdir(excel_dir_path)
    xls_files = [f for f in files if f.endswith(('.xlsx', '.xls'))]
    if len(files) is 0:
        raise FileNotFoundError('xls文件夹为空')
    for file in xls_files:
        wb = pd.ExcelFile(os.path.join(excel_dir_path, file), engine='openpyxl')
        sheets = wb.sheet_names
        print(f"处理{os.path.join(excel_dir_path, file)}")
        for sheet in sheets:
            df = pd.read_excel(os.path.join(excel_dir_path, file), sheet_name=sheet)
            df.to_csv(target + '\\' + file + sheet + '.txt')  # index=False 不保存索引
            # yield 1


def del_same_md5(oldpath: str, newpath: str):
    if len(os.listdir(oldpath)) == 0:
        raise FileNotFoundError('txt文件夹为空')
    files = os.listdir(oldpath)
    for file in files:
        if not os.path.exists(os.path.join(oldpath, file)):
            continue
        with open(os.path.join(oldpath, file), 'rb') as f:
            dataold = f.read()
            md5_old = hashlib.md5(dataold).hexdigest()
        if not os.path.exists(os.path.join(newpath, file)):
            continue
        with open(os.path.join(newpath, file), 'rb') as f:
            datanew = f.read()
            md5_new = hashlib.md5(datanew).hexdigest()
        if md5_old == md5_new:
            print(f'删除了内容相同的sheet页{file}')
            if os.path.exists(os.path.join(oldpath, file)):
                os.remove(os.path.join(oldpath, file))
            if os.path.exists(os.path.join(newpath, file)):
                os.remove(os.path.join(newpath, file))
    return True


# 获取字符串的md5
def get_string_md5(s):
    md5_obj = hashlib.md5()
    md5_obj.update(s.encode('utf-8'))
    return md5_obj.hexdigest()


# 多线程的方式xls转换成txt
def do_txt(compare_path: str):
    starttime = int(time.time())
    t_old = threading.Thread(target=xls_to_txt, args=(oldexcelsave, oldtxtsave))
    t_new = threading.Thread(target=xls_to_txt, args=(newexcelsave, newtxtsave))
    t_old.setDaemon(True)
    t_old.start()
    t_new.setDaemon(True)
    t_new.start()
    t_old.join()
    t_new.join()
    endtime = int(time.time())
    flag = del_same_md5(oldtxtsave, newtxtsave)
    print(endtime - starttime)
    time.sleep(1)
    if flag:
        exc_compare(compare_path)
        return True
    else:
        return False


def exc_compare(compare_path: str):
    if compare_path is '' or compare_path is None:
        return False
    else:
        subprocess.Popen([compare_path, oldtxtsave, newtxtsave])



if __name__ == '__main__':
    pass
    # run()
    # all_xls(oldexcelsave, oldtxtsave)
    # all_xls(newexcelsave, newtxtsave)
    # del_same_md5(oldtxtsave, newtxtsave)
